package com.loocan.answer

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.Window
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDialog
import com.leyou.sdk.ads.AdSdk
import com.leyou.sdk.ads.api.BannerAd
import com.leyou.sdk.ads.api.InterstitialAd
import com.leyou.sdk.ads.api.RewardVideoAd
import com.leyou.sdk.ads.config.AdCode
import com.leyou.sdk.ads.interfaces.FusionAdNative.BannerAdLoadListener
import com.leyou.sdk.ads.interfaces.FusionAdNative.InterstitialAdLoadListener
import com.leyou.sdk.ads.interfaces.FusionAdNative.RewardVideoAdLoadListener
import com.loocan.answer.databinding.ActivityMainBinding
import com.loocan.answer.utils.SoundPlayer
import com.loocan.answer.utils.StatusBarUtils
import com.loocan.answer.utils.dp
import com.loocan.answer.view.AnimatedButton
import com.loocan.answer.view.AnimatedButton.OnClickView


class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initData()
        initView()
    }

    private fun initData() {
        StatusBarUtils.setStatusTransparent(this)
        SoundPlayer.initialize(this)
        // 加载声音文件
        SoundPlayer.loadSound(this, R.raw.beijingyinyue, true);
        SoundPlayer.playSound()
    }

    override fun onResume() {
        super.onResume()
        SoundPlayer.playSound()
    }

    override fun onPause() {
        super.onPause()
        SoundPlayer.pauseSound()
    }

    private fun initView() {
        showCurrentQuestion()
    }

    private var currentQuestionIndex = 0

    private fun showCurrentQuestion() {
        binding.btnOption1.setBackgroundResource(R.drawable.btn11) // 正确样式
        binding.btnOption2.setBackgroundResource(R.drawable.btn11) // 正确样式
        binding.btnOption3.setBackgroundResource(R.drawable.btn11) // 正确样式
        binding.btnOption4.setBackgroundResource(R.drawable.btn11) // 正确样式
        val paddingInDp = 16.dp() // 假设你有 dp 转换的扩展函数
        binding.btnOption1.setPadding(paddingInDp, paddingInDp, paddingInDp, paddingInDp)
        binding.btnOption2.setPadding(paddingInDp, paddingInDp, paddingInDp, paddingInDp)
        binding.btnOption3.setPadding(paddingInDp, paddingInDp, paddingInDp, paddingInDp)
        binding.btnOption4.setPadding(paddingInDp, paddingInDp, paddingInDp, paddingInDp)


        if (currentQuestionIndex >= BaseContents.quizQuestions.size) {
            // 题目已结束
            binding.tvQuestion.text = "题目已完成！"
            return
        }

        val currentQuestion = BaseContents.quizQuestions[currentQuestionIndex]
        binding.tvQuestion.text = currentQuestion.question

        binding.btnOption1.text = currentQuestion.options[0]
        binding.btnOption2.text = currentQuestion.options[1]
        binding.btnOption3.text = currentQuestion.options[2]
        binding.btnOption4.text = currentQuestion.options[3]

        binding.btnOption1.settOnClickView(object : OnClickView {
            override fun onClick(text: String) {
                checkAnswer1(binding.btnOption1, text)
            }
        })
        binding.btnOption2.settOnClickView(object : OnClickView {
            override fun onClick(text: String) {
                checkAnswer1(binding.btnOption2, text)
            }
        })
        binding.btnOption3.settOnClickView(object : OnClickView {
            override fun onClick(text: String) {
                checkAnswer1(binding.btnOption3, text)
            }
        })
        binding.btnOption4.settOnClickView(object : OnClickView {
            override fun onClick(text: String) {
                checkAnswer1(binding.btnOption4, text)
            }
        })
    }

    private fun checkAnswer1(view: AnimatedButton, text: String) {
        getAd2()
        if (BaseContents.quizQuestions.size <= currentQuestionIndex) {
            return
        }
        val currentQuestion = BaseContents.quizQuestions[currentQuestionIndex]
        val selectedAnswer = text.takeIf {
            it.startsWith("A") || it.startsWith("B") || it.startsWith("C") || it.startsWith("D")
        }?.split(".")?.get(0)?.trim()

        if (selectedAnswer == currentQuestion.correctAnswer) {
            view.setBackgroundResource(R.drawable.btn13) // 正确样式
            // 可以播放音效或提示动画
            showFeedbackDialog(true, view)
        } else {
            view.setBackgroundResource(R.drawable.btn12) // 错误样式
            showFeedbackDialog(false, view)
        }
        val paddingInDp = 16.dp() // 假设你有 dp 转换的扩展函数
        view.setPadding(paddingInDp, paddingInDp, paddingInDp, paddingInDp)
    }


    private fun getAd2() {
        val adCode = AdCode.Builder()
            .setCodeId("31036102")
            .build()
        AdSdk.getAdManager().createAdNative(this)
            .loadBannerAd(adCode, object : BannerAdLoadListener {
                override fun onBannerAdLoad(bannerAd: BannerAd) {
                    binding.adLayout.removeAllViews()
                    val frameLayout = FrameLayout(this@MainActivity)
                    frameLayout.addView(bannerAd.getAdView())
                    binding.adLayout.addView(frameLayout)
                }

                override fun onError(code: Int, msg: String?) {

                }
            })
    }


    override fun onDestroy() {
        super.onDestroy()
        SoundPlayer.stopSound()
    }

    private fun showFeedbackDialog(isCorrect: Boolean, view: AnimatedButton) {
        val dialog = AppCompatDialog(this)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) // 移除标题栏
        dialog.setContentView(R.layout.dialog_feedback) // 设置自定义布局
        dialog.setCancelable(false) // 设置是否可以通过点击外部来取消Dialog
        dialog.setCanceledOnTouchOutside(false) // 设置点击外部是否可以取消Dialog
        // 设置背景为透明
        val window = dialog.window
        window?.setBackgroundDrawableResource(android.R.color.transparent)
        dialog.show()
        val icon = dialog.findViewById<ImageView>(R.id.ivIcon)
        val tvMessage = dialog.findViewById<TextView>(R.id.tvMessage)
        val tvMessage1 = dialog.findViewById<TextView>(R.id.tvMessage1)
        val ll_image = dialog.findViewById<LinearLayout>(R.id.ll_image)
        val tv_next = dialog.findViewById<TextView>(R.id.tv_next)
        // 执行弹窗动画
        icon?.animate()?.apply {
            scaleX(0f).scaleY(0f).alpha(0f)
            withEndAction {
                icon?.animate()?.scaleX(1f)?.scaleY(1f)?.alpha(1f)?.setDuration(300)?.start()
            }
        }

        if (isCorrect) {
            icon?.setImageResource(R.drawable.ic_check_circle)
            tvMessage?.setText("恭喜，回答正确！")
            tvMessage1?.setText("恭喜你获取金币奖励")
            tv_next?.setText("领取更多奖励")
            ll_image?.visibility = View.VISIBLE
        } else {
            icon?.setImageResource(R.drawable.ic_close_circle)
            tvMessage?.setText("回答错误！")
            tvMessage1?.setText("连对结束，复活可保持连对次数")
            tv_next?.setText("立即复活")
            ll_image?.visibility = View.GONE
        }

        dialog.findViewById<ImageView>(R.id.iv_close)?.setOnClickListener {
            dialog.dismiss()
            currentQuestionIndex++
            showCurrentQuestion()
        }
        dialog.findViewById<LinearLayout>(R.id.ll_next)?.setOnClickListener {
            dialog.dismiss()
            getAd()
        }
    }

    fun getAd() {
        val adCode = AdCode.Builder()
            .setCodeId("31036099")
            .build()
        AdSdk.getAdManager().createAdNative(this)
            .loadInterstitialAd(adCode, object : InterstitialAdLoadListener {
                override fun onError(code: Int, msg: String?) {
                    currentQuestionIndex++
                    showCurrentQuestion()
                }

                override fun onInterstitialAdLoad(interstitialAd: InterstitialAd?) {
                    interstitialAd?.showAd(this@MainActivity)
                    interstitialAd?.setAdInteractionListener(object :
                        InterstitialAd.AdInteractionListener {
                        override fun onAdClicked() {
                        }

                        override fun onAdShow() {
                        }

                        override fun onAdClose() {
                            currentQuestionIndex++
                            showCurrentQuestion()
                        }
                    })
                }
            })

        /*AdSdk.getAdManager().createAdNative(this)
            .loadRewardVideoAd(adCode, object : RewardVideoAdLoadListener {
                override fun onError(code: Int, msg: String?) {
                }

                override fun onRewardVideoAdLoad(interstitialAd: RewardVideoAd?) {
                    interstitialAd?.showAd(this@MainActivity)

                }
            })*/
    }
}